﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Enterprise.Exceptions;
using System.Data.SqlClient;

namespace Enterprise
{
    /// <summary>
    /// Config values
    /// </summary>
    public static class Config
    {
        /// <summary>
        /// Reads the ConnectionString from web.config.
        /// If the connectionstring isn't provided, an exception is thrown.
        /// </summary>
        /// <returns>Connectionstring</returns>
        public static string ConnectionString()
        {
            try
            {
                return ConfigurationManager.ConnectionStrings["EPSConnectionString"].ConnectionString;
            }
            catch {throw new Error(Message.ConnectionStringIsMissing);}
        }

        /// <summary>
        /// Selects next available id
        /// </summary>
        /// <returns></returns>
        public static string CreateID()
        {
            SqlConnection Conn = new SqlConnection(Config.ConnectionString());
            try
            {
                SqlCommand command = new SqlCommand("SELECT Max(id)+1 AS LASTID FROM Objects", Conn);
                Conn.Open();
                SqlDataReader dr = command.ExecuteReader();

                if (dr.Read())
                    return Convert.ToString(dr["LASTID"]);
                return null;
            }
            finally
            {
                Conn.Close();
            }
        }


        /// <summary>
        /// Selects startpage id
        /// </summary>
        /// <returns></returns>
        public static string GetStartPageID()
        {
            SqlConnection Conn = new SqlConnection(Config.ConnectionString());
            try
            {
                SqlCommand command = new SqlCommand("SELECT ID FROM SiteMap WHERE IsStartPage=1", Conn);
                Conn.Open();
                SqlDataReader dr = command.ExecuteReader();

                if (dr.Read())
                    return Convert.ToString(dr["ID"]);
                return null;
            }
            finally
            {
                Conn.Close();
            }
        }
    }
}
